package com.woniuxy.school.dietary.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.school.dietary.store.entity.DietTimeConfig;
import com.woniuxy.school.dietary.store.mapper.DietTimeConfigMapper;
import com.woniuxy.school.dietary.store.model.from.FindDietTimeFrom;
import com.woniuxy.school.dietary.store.service.DietTimeConfigService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 吴彦祖
 * @since 2025年05月14日
 */
@Service
public class DietTimeConfigServiceImpl extends ServiceImpl<DietTimeConfigMapper, DietTimeConfig> implements DietTimeConfigService {
     @Resource
     private DietTimeConfigMapper dietTimeConfigMapper;
    @Override
    public Boolean findDietTime(FindDietTimeFrom from) {
        QueryWrapper<DietTimeConfig> wrapper = new QueryWrapper<>();
        wrapper.eq("storeId", from.getStoreId());
        DietTimeConfig config = dietTimeConfigMapper.selectOne(wrapper);
        if(config==null) throw new RuntimeException("该商家还未设置营业时间");
        //下单时间
        LocalDateTime time = from.getOrderTime();
        Instant instant = time.atZone(ZoneId.systemDefault()).toInstant();
        //获取时间戳
        Long orderTimeStamp1 = instant.getEpochSecond();
        //开始营业时间
        LocalTime time1 = config.getStartTime();
        Long orderTimeStamp2 = localDateTimeToStamp(time1);
        //结束营业时间
        LocalTime time2 = config.getEndTime();
        Long orderTimeStamp3 = localDateTimeToStamp(time2);
        if(orderTimeStamp1>=orderTimeStamp2&&orderTimeStamp1<=orderTimeStamp3){
            return true;
        }

        //将字符串转时间类
        return false;
    }
    /**
     * 时间转换公用方法 localDateTime转时间戳
     */
    public static Long localDateTimeToStamp(LocalTime localTime){
       //获取当前日期
        LocalDate today = LocalDate.now();
        //合并成时间
        LocalDateTime time = LocalDateTime.of(today, localTime);
        //获取时区
        Instant instant = time.atZone(ZoneId.systemDefault()).toInstant();
        //获取时间戳
        Long second = instant.getEpochSecond();
        return second;
    }
}
